package Stream.中间操作符;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/*
    中间操作符：distinct
    strings.stream()把集合转为一个流，然后通过 distinct 去重
    然后通过collect来把符合条件的流回收，并且 通过Collectors.toList() 来把结果进一步转为list集合
 */
public class Distinct {
    public static void main(String[] args) {

        List<String> strings = Arrays.asList("1","2","1","1","dfd","fdfew","dfd");

        List<String> collect = strings.stream().distinct().collect(Collectors.toList());
        System.out.println(collect);//[1, 2, dfd, fdfew]

        List<DistinctTest> distinctTests = new ArrayList<>();
        distinctTests.add(new DistinctTest(1,"李锦龙"));
        distinctTests.add(new DistinctTest(1,"李锦龙"));
        List<DistinctTest> collect1 = distinctTests.stream().distinct().collect(Collectors.toList());
        System.out.println(collect1);// 如果DistinctTest类重写了equals和hashcode方法（少一个都不行），那么对象就会去重
    }
}

class DistinctTest{
    int aget;
    String name;

    public int getAget() {
        return aget;
    }

    public void setAget(int aget) {
        this.aget = aget;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DistinctTest() {
    }

    public DistinctTest(int aget, String name) {
        this.aget = aget;
        this.name = name;
    }

    @Override
    public String toString() {
        return "DistinctTest{" +
                "aget=" + aget +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        DistinctTest that = (DistinctTest) o;
        return aget == that.aget && Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(aget, name);
    }
}
